/**
 *    @file       perlregexp.cpp
 *
 *    @brief      
 *    @details
 *
 *    @version    1.0
 *    @date       01/26/2014 12:48:43 AM
 *
 *    @author     Theophilus (), wangtf418@gmail.com
 */
#ifndef __WITHOUT_PCRE__
#include "perlregexp.h"

perlregexp::perlregexp() : m_pcre_pattern(NULL)
{

}

perlregexp::~perlregexp()
{
	if (m_pcre_pattern)
	{
		free(m_pcre_pattern);
		m_pcre_pattern = NULL;
	}
}

bf_int_t perlregexp::compile(const bf_char_t *pattern, bf_int_t option /* = 0 */)
{
	if(!pattern)
	{
		return BF_ERROR;
	}
	const bf_char_t *err_msg;
	if (m_pcre_pattern)
	{
		free(m_pcre_pattern);
		m_pcre_pattern = NULL;
	}
	m_pcre_pattern = pcre_compile2(pattern, option, &m_errno, &err_msg, &m_errpos, NULL);
	if (m_pcre_pattern == NULL)
	{
		m_errmsg = err_msg;
		return BF_FAIL;
	}
	return BF_SUCC;
}

bf_int_t perlregexp::execute(const bf_char_t *str, bf_int_t strlen, bf_uint_t max_groupno /* = 10 */, bf_int_t option /* = 0 */, bf_int_t startpos /* = 0 */)
{
	if (!m_pcre_pattern || !str || strlen <= 0 || max_groupno < 0 || startpos < 0)
	{
		return BF_ERROR;
	}
	m_match.clear();
	m_match.resize(max_groupno * 3);

	bf_int_t matchnum = pcre_exec(m_pcre_pattern, NULL, str, strlen, startpos, option, &m_match[0], max_groupno * 3);
	if (matchnum <= 0)
	{
		return BF_FAIL;
	}
	m_match.resize(matchnum * 3);

	return BF_SUCC;
}

#endif

